package com.pet.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Administrator on 2016-1-11.
 */
public class FileUtils {

    /**
     * 根据文件名称返回文件后缀，比如 输入 test.jsp 返回 .jsp
     * @param fileName
     * @return
     */
    public static String getExtension(String fileName){
        int lastD = fileName.lastIndexOf(".");
        if(lastD == -1) return fileName;
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 保存文件
     * @param stream
     * @param path
     * @throws IOException
     */
    public static void saveFileFromInputStream(InputStream stream, String path) throws IOException{
        FileOutputStream outputStream = null;
        try{
            outputStream = new FileOutputStream(path);
            int byteCount = 0;
            byte[] bytes = new byte[1024];
            while ((byteCount = stream.read(bytes)) != -1){
                outputStream.write(bytes, 0, byteCount);
            }
        }finally {
            try {
                if(outputStream != null) outputStream.close();
                stream.close();
            } catch (IOException e) {
            }
        }
    }

    public static void main(String[] args){
        System.out.println(getExtension("test.jsp"));
    }
}
